import { TOUCHER_COLLIDER_TAG } from "../Common/Constant";
import SingleBlockController from "./SingleBlockController";

const { ccclass, property } = cc._decorator;

@ccclass
export default class ToucherController extends cc.Component {
    public static I: ToucherController;

    @property(cc.Node)
    layerMap: cc.Node = null;

    private _target: SingleBlockController;

    public onLoad() {
        ToucherController.I = this;
        this.node.active = false;
        this.node.getComponent(cc.Collider).tag = TOUCHER_COLLIDER_TAG;
        this.layerMap.on(cc.Node.EventType.TOUCH_START, this.__onTouchStart, this);
        this.layerMap.on(cc.Node.EventType.TOUCH_MOVE, this.__onTouchMove, this);
        this.layerMap.on(cc.Node.EventType.TOUCH_END, this.__onTouchEnd, this);
       
    }

    public matchTarget(target: SingleBlockController): void {
        this._target = target;
    }

    public releaseTarget(): void {
        this._target = null;
    }

    private __onTouchStart(e: cc.Event.EventTouch): void {
        this.node.active = true;
        
        
        this.__onTouchMove(e);
        
        //e.target._touchListener.setSwallowTouches(false);
    }

    private __onTouchMove(e: cc.Event.EventTouch): void {
        this.node.setPosition(this.layerMap.convertToNodeSpaceAR(e.getLocation()));
        //e.target._touchListener.setSwallowTouches(false);
    }

    private __onTouchEnd(e: cc.Event.EventTouch): void {
        if (this._target) {
            this._target.collect();
            this._target = null;
        }
        this.node.active = false;
        //e.target._touchListener.setSwallowTouches(false);
        
    }
}
